package com.atguigu.crowd.mvc.handler;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitterReturnValueHandler;

import com.atguigu.crowd.entity.Role;
import com.atguigu.crowd.service.api.RoleService;
import com.atguigu.crowd.util.ResultEntity;
import com.github.pagehelper.PageInfo;

@Controller
public class RoleHandler {

	@Autowired
	private RoleService roleService;
	
	//删除对象（单条、批量）
	@PreAuthorize("hasAuthority('role:delete')")
	@ResponseBody
	@RequestMapping("/role/remove/by/id/array.json")
	public ResultEntity<String> removeRole(@RequestBody List<Integer> ids){
		roleService.removeRole(ids);
		return ResultEntity.successWithoutData();
	}
	
	//更新对象
	@PreAuthorize("hasAuthority('role:update')")
	@ResponseBody
	@RequestMapping("/role/edit.json")
	public ResultEntity<String> editRole(Role role){
		roleService.editRole(role);
		return ResultEntity.successWithoutData();
	}
	
	//添加对象
	@PreAuthorize("hasAuthority('role:add')")
	@ResponseBody
	@RequestMapping("/role/add.json")
	public ResultEntity<String> addRole(Role role){
		roleService.addRole(role);
		return ResultEntity.successWithoutData();
	} 
	
	//分页显示对象
	//@PreAuthorize("hasRole('角色经理')")//注解分配角色分页页面的权限
	 
	@ResponseBody 
	@RequestMapping("/role/get/page/info.json")
	public ResultEntity<PageInfo<Role>> getPageInfo(
				@RequestParam(value="pageNum", defaultValue="1") Integer pageNum,
				@RequestParam(value="pageSize", defaultValue="5") Integer pageSize,
				@RequestParam(value="keyword", defaultValue="") String keyword
			) {
		
		// 调用Service方法获取分页数据
		PageInfo<Role> pageInfo = roleService.getPageInfo(pageNum, pageSize, keyword);
		
		// 封装到ResultEntity对象中返回（如果上面的操作抛出异常，交给异常映射机制处理）
		return ResultEntity.successWithData(pageInfo);
	}
}
